package com.qf.filter;

import com.qf.pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 鉴权过滤器
 * 拦截所有请求，判断tomcat的session中是否由用户对象信息
 * 如果有放行
 * 如果没有，说明用户未登录，需要重新登录
 */
@WebFilter("/*")
public class PermFilter implements Filter{

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1、获取用户的访问路径
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        //获取到用户访问路径
        String uriStr = request.getRequestURI();
        System.out.println(uriStr);
        //2、判断用户路径，放行所有静态资源，放行用户登录路径、用户注册、首页、商品查询等路径
        //判断路径的扩展名。如果是js文件放行，jsp文件与js文件无法使用contains判断
        if (uriStr.lastIndexOf(".") > 0) {
            String extStr = uriStr.substring(uriStr.lastIndexOf("."));
            if (extStr != null) {
                if (".js".equals(extStr)) {
                    //放行
                    filterChain.doFilter(servletRequest, servletResponse);
                    return;
                }
            }
        }
        if (uriStr.contains("/login") || uriStr.contains("/code")
                ||uriStr.contains("/user") || uriStr.contains("/register")
                || uriStr.contains("/type")|| uriStr.contains("/goods")
                || uriStr.contains("/index")
                || uriStr.contains(".css")|| uriStr.contains("/admin")
                || uriStr.contains(".jpg") || uriStr.contains(".png")
                || uriStr.contains(".gif") || uriStr.contains(".eot")
                || uriStr.contains(".svg") || uriStr.contains(".ttf")
                || uriStr.contains(".woff") || uriStr.contains(".woff2") ){
            //放行
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        //3、获取会话session对象
        HttpSession session = request.getSession();
        //4、判断会话中是否有用的用户的对象信息
        User user = (User) session.getAttribute("loginUser");
        if (user != null){
            //5、有放行
            filterChain.doFilter(servletRequest, servletResponse);
        }else {
            //6、没有，让用户重定向到登录界面重新登录
            response.sendRedirect("/login.jsp");
        }

    }

    @Override
    public void destroy() {

    }
}
